import { createBanner, getBannerList, deleteBanner, updateBanner,getAreaList } from './advertisingListServ'
// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge, pick } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
// 引入接口文件
import { getAdvertising } from './advertisingListServ.js'
import { makeAddress } from 'utils/util'

// 初始默认状态
const defultState = {
  loading: false,
  btnLoading: false,
  xxx: '1',
  hrefModalObj: {
    visible:false,
    hrefType:'4',
  },
  hitsModalObj:{
    visible:false,
  },
  areaList: [],
  // hrefType 链接类型(1:楼盘 2：专题活动 3：资讯 4:外部链接 5：活动)
  biz:{
    1: {//专题活动
      queryForm: {},
      rowSelection_type:'radio',
    },
    2: {//楼盘
      queryForm: {},
      rowSelection_type:'radio',
    },
    3: {//资讯
      queryForm: {}  ,
      rowSelection_type:'radio',
    },
    4: {//外部链接
      queryForm: {}  ,
      rowSelection_type:'radio',
    },
    5: {//活动
      queryForm: {}  ,
      rowSelection_type:'radio',
    },
    6: {//我要推介
      queryForm: {}  ,
      rowSelection_type:'radio',
    },
    7: {//预约看房
      queryForm: {}  ,
      rowSelection_type:'radio',
    },
    9: {//优惠券
      queryForm: {}  ,
      rowSelection_type:'radio',
    },
    10: {//点击量
      queryForm: {}  ,
      rowSelection_type:'radio',
    },
  },

  channelIndex: '1',
  // bannerList: [],
  bannerList: {
    1: [],
    2: [],
  },
  bannerList_old: {
    1: [],
    2: [],
  },
  newItemList: {
    1: [],
    2: [],
  },
  currentItem: {
    "url": "",
    "href": "",
    "type": 1,
    "ord": "1",
    "published": "0",
    "channel": "101",
    "title": "轮播图" ,
    'hrefType': '4',
    'slideshowId': '',
    'startDate':'' ,
    'endDate': '',
    'params': {},
    // 'createPerson': '',
    // 'createTime': '',
  },
  hrefVisible: true,
  writeUrl: '',
  nowUrlChange: '',
  pageInfo: {
    1: {
      pageNo: 1,
      pageSize: 10,
      total: 0,
    },
    2: {
      pageNo: 1,
      pageSize: 10,
      total: 0,
    },
  },
  areaList1:[],
  newBanner: false,
  status: '',
  hrefType: '4',//路径面板tab索引
  mpUrlsObj: {
    mpUrls: [],
    expandedKeys: ['0',],
    selectedKeys: [],
    onExpand: true,
    autoExpandParent: true,
    link: '',
  }
}

// 声明module
const tmpModule = {
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({pathname, query}) => {
        // 页面路由匹配时执行
        if ('' + tmpModule.pathname === '' + pathname) {
          dispatch({type: 'getBannerList', payload: {channelIndex: 1}})
          dispatch({type: 'getBannerList', payload: {channelIndex: 2}})
          dispatch({type: 'getAreaList', payload: {}})
        }
      })
    },
  },
  
  // 方法列表
  effects: {
    * getBannerList ({payload}, {put, call, select}) {
      let {channelIndex, bannerList,bannerList_old, pageInfo,} = yield select(state => state[tmpModule.namespace])
      channelIndex = payload.channelIndex || channelIndex
      let channel = channelIndex == 1 ? '101' : '201'
      payload.channel = channel
      let params = {
        channel: channel,
        pageNo: payload.pageNo || pageInfo[channelIndex].pageNo || 1,
        pageSize: payload.pageSize || pageInfo[channelIndex].pageSize || 10,
      }
      try {
        // delete payload.channelIndex
        const {success=false, rows = [], total = 0, pageNo=1, pageSize=10} = yield call(getBannerList, params)
        if (success) {
          rows.map((item,index)=>{
            item.key=index
            item.idx=index
            // 有效时间
            let {date=null,startDate=null,endDate=null}=item
            item.key = item.productId;
            item.name = item.projectName;
            if(!date&&(startDate||endDate)){
              item.date=[startDate||null,endDate||null]
            }
            item.ord=item.ord && Number(item.ord)  ||1000
          })
          bannerList[channelIndex] = rows
          bannerList_old[channelIndex] = rows
          pageInfo[channelIndex] = {...pageInfo[channelIndex], pageNo, pageSize, total}
          yield put({type: 'updateStore', payload: {bannerList,bannerList_old, pageInfo}})
        }
      } catch (e) {
        console.log(e)
      }
    },
    * createBanner ({payload}, {put, call, select}) {
      let {channelIndex,newItemList={},pageInfo} = yield select(state => state[tmpModule.namespace])
      try {
        let {arr=[],index='',cbk}=payload
        let channel = channelIndex == 1 ? '101' : '201'
        payload.channel = channel
        arr.map((item,index)=>{
          let [startDate,endDate]=item.date||[];
          arr[index]={
            ...pick(item, ['url','href','type','ord','published','channel','title','hrefType','startDate','endDate','params']),startDate, endDate ,channel
          }
           // msgArr.push(`图${index + 1}${msg}`)
        })
        let params = {
          slideshowCreateReqDtos: arr,
          channel,
        }
        const {success} = yield call(createBanner, parse(params))
        yield put({type: 'updateStore', payload: {loading: false, btnLoading: false,}})
        if (success) {
          cbk&&cbk()
          message.success('操作成功！')
          pageInfo[channelIndex].pageNo=1
          newItemList[channelIndex]=[]
          yield put({type: 'updateStore', payload: {newItemList, pageInfo}})
          yield put({type: 'getBannerList', payload: {pageNo: 1}})
        }
      } catch (e) {
        console.log(e)
      }
    },
     //获取省市
    * deleteBanner ({payload}, {put, call, select}) {
      let {channelIndex} = yield select(state => state[tmpModule.namespace])
      // channelIndex=payload.channelIndex||channelIndex
      let channel = channelIndex == 1 ? '101' : '201'
      let {slideshowId} =payload.item||{}
      // payload.channel = channel
      let params={
        slideshowId,
        channel
      }
      try {
        // console.warn(payload)
        const {success, rows} = yield call(deleteBanner, parse(params))
        if (success) {
          message.success('删除成功！')
          yield put({type: 'getBannerList', payload: {pageNo: 1}})
        }
      } catch (e) {
        console.log(e)
      }
    },
    
    * updateBanner ({payload}, {put, call, select}) {
      let {channelIndex} = yield select(state => state[tmpModule.namespace])
      // channelIndex=payload.channelIndex||channelIndex
      let channel = channelIndex == 1 ? '101' : '201'
      let {arr=[],cbk}=payload
      let slideshowUpdateReqDtos=[]
      arr.map((item,index)=>{
        let {date,url='',ord=''}=item||{}
        let [startDate,endDate]=date||[];
        slideshowUpdateReqDtos.push(
          {
            ...pick(item, ['url','href','hrefType','type','ord','published','channel','title','slideshowId','startDate','endDate','params']),startDate, endDate ,channel
          }
        )
      })
      let params={slideshowUpdateReqDtos}
      try {
        const {success, rows} = yield call(updateBanner, parse(params))
        yield put({type: 'updateStore', payload: {loading: false, btnLoading: false,}})
        if (success) {
          cbk&&cbk()
          message.success('更改成功！')
          yield put({type: 'getBannerList', payload: {pageNo: 1}})
        }
      } catch (e) {
        console.log(e)
      }
    },
    *getAreaList({ payload }, { put, call, select }){
      const { data, success } = yield call(getAreaList);
      if(success) {
        let areaList = []
        let arr = [data[0]]
        let attr = [data[data.length-1]]
        data[0] = {
          label:"北京",
          value:"110100",
          children:arr
        }
        data[data.length-1]={
          label:"澳门",
          value:"820000",
          children:attr
        }
        //去掉第三级，
        areaList = makeAddress(data,2)
        yield put({ type: 'updateStore',payload:{areaList}})
      }
    },
  },
  // 存入状态机
  reducers: {
    updateStore (preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
